package com.ruoyi.system.service.impl;

import com.ruoyi.common.annotation.UserDataIsolation;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.domain.DeviceProperty;
import com.ruoyi.system.domain.DevicePropertyValue;
import com.ruoyi.system.domain.vo.DevicePropertyValueResultVO;
import com.ruoyi.system.domain.vo.DevicePropertyValueVO;
import com.ruoyi.system.mapper.DevicePropertyValueMapper;
import com.ruoyi.system.service.IDevicePropertyService;
import com.ruoyi.system.service.IDevicePropertyValueService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
@Service
@Slf4j
public class DevicePropertyValueServiceImpl implements IDevicePropertyValueService {

    @Autowired
    private DevicePropertyValueMapper devicePropertyValueMapper;
    @Autowired
    private IDevicePropertyService devicePropertyService;

    @Override
    @UserDataIsolation(tableAlias = "t1")
    public List<DevicePropertyValueResultVO> queryDeviceValueByDeviceId(DevicePropertyValue devicePropertyValue) {
        //查询所有的配置字段
        DeviceProperty deviceProperty = new DeviceProperty();
        deviceProperty.setId(devicePropertyValue.getPropertyId());
        deviceProperty.setPropertyGroup(deviceProperty.getPropertyGroup());
        List<DeviceProperty> deviceProperties = devicePropertyService.queryPageList(deviceProperty);
        if (CollectionUtils.isEmpty(deviceProperties)) {
            return new ArrayList<>();
        }
        List<DevicePropertyValueVO> result = new ArrayList<>();
        //查询该产品的属性值
        List<DevicePropertyValue> devicePropertyValues = devicePropertyValueMapper.queryDeviceValue(devicePropertyValue);
        if (CollectionUtils.isEmpty(devicePropertyValues)) {
            for (DeviceProperty property : deviceProperties) {
                DevicePropertyValueVO valueVO = initValueVO(null, property, devicePropertyValue.getDeviceId());
                if (valueVO != null) {
                    result.add(valueVO);
                }
            }
            return initResultVO(result);
        }
        //获取已赋值的属性
        for (DevicePropertyValue value : devicePropertyValues) {
            for (DeviceProperty property : deviceProperties) {
                if (value.getPropertyId().compareTo(property.getId()) == 0) {
                    DevicePropertyValueVO valueVO = initValueVO(value, property, devicePropertyValue.getDeviceId());
                    if (valueVO != null) {
                        result.add(valueVO);
                    }
                    break;
                }
            }
        }
        //获取未赋值的属性
        Set<Integer> propertyIds = devicePropertyValues.stream().map(DevicePropertyValue::getPropertyId).collect(Collectors.toSet());
        deviceProperties.stream().forEach(a -> {
            if (!propertyIds.contains(a.getId())) {
                DevicePropertyValueVO valueVO = initValueVO(null, a, devicePropertyValue.getDeviceId());
                if (valueVO != null) {
                    result.add(valueVO);
                }
            }
        });
        return initResultVO(result);
    }

    /**
     * 获取产品额外属性值结果
     *
     * @param devicePropertyValueVOS
     * @return
     */
    private List<DevicePropertyValueResultVO> initResultVO(List<DevicePropertyValueVO> devicePropertyValueVOS) {
        if (CollectionUtils.isEmpty(devicePropertyValueVOS)) {
            return new ArrayList<>();
        }
        Map<String, List<DevicePropertyValueVO>> listMap = devicePropertyValueVOS.stream().collect(Collectors.groupingBy(DevicePropertyValueVO::getPropertyGroup));
        List<DevicePropertyValueResultVO> resultVOS = new ArrayList<>();
        for (Map.Entry<String, List<DevicePropertyValueVO>> entry : listMap.entrySet()) {
            DevicePropertyValueResultVO resultVO = new DevicePropertyValueResultVO();
            resultVO.setPropertyGroup(entry.getKey());
            List<DevicePropertyValueVO> value = entry.getValue();
            Collections.sort(value, new Comparator<DevicePropertyValueVO>() {
                @Override
                public int compare(DevicePropertyValueVO o1, DevicePropertyValueVO o2) {
                    return o1.getOrderNum() - o2.getOrderNum();
                }
            });
            resultVO.setDevicePropertyValueVOS(value);
            resultVOS.add(resultVO);
        }
        return resultVOS;
    }

    @Override
    @UserDataIsolation
    public Boolean saveOrUpdate(List<DevicePropertyValue> devicePropertyValues, String userName, Long companyId) {
        devicePropertyValues.forEach(a -> {
            if (a.getDeviceId() == null || a.getPropertyId() == null) {
                throw new CustomException("产品id或属性id不能为空");
            }
        });
        //获取需要修改的属性
        List<DevicePropertyValue> updateProductList = devicePropertyValues.stream().filter(a -> !StringUtils.isEmpty(a.getId())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(updateProductList)) {
            for (DevicePropertyValue value : updateProductList) {
                devicePropertyValueMapper.updateDeviceProperty(value);
            }
        }
        //获取需要新增的属性
        List<DevicePropertyValue> saveProductList = devicePropertyValues.stream().filter(a -> StringUtils.isEmpty(a.getId()) && !StringUtils.isEmpty(a.getValue())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(saveProductList)) {
            for (DevicePropertyValue value : saveProductList) {
                value.setCompanyId(companyId);
                value.setCreateBy(userName);
                value.setCreateTime(new Date());
                devicePropertyValueMapper.saveDeviceProperty(value);
            }
        }
        return true;
    }

    @Override
    @UserDataIsolation
    public Boolean deleteDevicePropertyValue(DevicePropertyValue devicePropertyValue) {
        return devicePropertyValueMapper.deleteDevicePropertyValue(devicePropertyValue) > 0;
    }

    /**
     * 获取产品属性值VO
     *
     * @param value
     * @param property
     * @param deviceId
     * @return
     */
    private DevicePropertyValueVO initValueVO(DevicePropertyValue value, DeviceProperty property, Integer deviceId) {
        if (property == null) {
            return null;
        }
        DevicePropertyValueVO valueVO = new DevicePropertyValueVO();
        valueVO.setDataType(property.getDataType());
        if (value != null) {
            valueVO.setValue(value.getValue());
            valueVO.setId(value.getId());
        }
        valueVO.setDeviceId(deviceId);
        valueVO.setOrderNum(property.getOrderNum());
        valueVO.setPropertyGroup(property.getPropertyGroup());
        valueVO.setPropertyId(property.getId());
        valueVO.setPropertyName(property.getPropertyName());
        return valueVO;
    }
}
